//创建购物车模块
angular.module("myapp")
.factory('cart',function(){
	var cartData = [];
	return{
		addProduct:function(title,sold,price){//把商品添加到购物车
			var addItem = false;//是否在购物车存在
			//遍历数组
			for(var i = 0;i<cartData.length;i++){
				if(cartData[i]["title"] == title){
					cartData[i].count++;
					addItem = true;
					break;
				}
			}
			if(!addItem){//如果没在购物车
				cartData.push({
					title:title,
					sold:sold,
					price:price,
					count:1
				})
			}
		},
		removeProduct:function(title){//删除指定title的产品
			for(var i = 0;i<cartData.length;i++){
				if(cartData[i]["title"] == title){
					cartData.splice(i,1);
					break;
				}
			}
		},
		getProducts:function(){//返回商品详情数组
			return cartData;
		}
	}
})
// 购物车商品信息展示
angular.module('myapp')
.controller('cartController',function($scope,cart){

	$scope.cartData = cart.getProducts();
	console.log($scope.cartData);
	$scope.total = function(){
		var sum = 0;
		for(var i = 0;i<$scope.cartData.length;i++){
			sum+=($scope.cartData[i]['price']) * ($scope.cartData[i]['count'])
		}
		sum=parseInt(sum*10)/10
		return sum;
	};
	$scope.fnjia = function(jia){
		for(var i = 0;i<$scope.cartData.length;i++){
			if($scope.cartData[i]['title']==jia['title']){
				$scope.cartData[i]['count']+=1;
			}
		}
	};
	$scope.fnjian = function(jian){
		for(var i = 0;i<$scope.cartData.length;i++){
			if($scope.cartData[i]['count']==0){
				$scope.cartData[i]['count']=0;
			}else{
				if($scope.cartData[i]["title"]==jian["title"]){
					$scope.cartData[i]['count']-=1;
				}	
			}
		}
	};
})